#!/usr/bin/evn python
# coding=utf-8

import requests
import json
# import datetime_helper, except_helper, log_helper, random_helper
# import datetime_helper, except_helper, random_helper, log_helper

from .datetime_helper import get_timestamp13
from .random_helper import get_number_for_range
from .except_helper import get_detailtrace
from loguru import logger

# 移动号码段
cm_phone_number_segment = ['134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '157', '158', '159',
                           '1705', '178', '182', '183', '184', '187', '188']
# 联通号码段
cu_phone_number_segment = ['130', '131', '132', '145', '155', '156', '1707', '1708', '1709', '175', '176', '185', '186']
# 电信号码段
ct_phone_number_segment = ['133', '153', '1700', '1701', '173', '177', '180', '181', '189']


def get_QCellCore(mobile):
    """获取手机号码归属地"""
    # Http访问头信息
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Encoding": "gzip, deflate, sdch, br",
        "Accept-Language": "zh-CN,zh;q=0.8",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "Content-Type": "application/x-www-form-urlencoded",
        "Host": "sp0.baidu.com",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    }
    # 生成时间戳
    t = get_timestamp13()
    jq_code_left = str(get_number_for_range(1102032000000000000000, 1102032999999999999999))
    jq_code_right = t - get_number_for_range(1000, 100000)
    # 拼接查询url地址
    url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api_offer.php?query=' + mobile + '&co=&resource_id=6004&t=' + str(
        t) + '&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery' + str(jq_code_left) + '_' + str(
        jq_code_right) + '&_=' + str(
        jq_code_right + get_number_for_range(1, 5))
    params = {}
    try:
        # 执行http请求
        r = requests.get(url, json=params, headers=headers, verify=False)
        # 对返回的内容进行编码处理，防止乱码
        if r.encoding.lower() == 'gbk':
            result = r.content.decode('gbk')
        elif r.encoding.lower() == 'gb2312' or r.apparent_encoding == 'GB2312':
            result = r.content.decode('gb2312')
        else:
            result = r.content.decode('utf-8')
    except Exception as e:
        # 获取程序调用堆栈的日志
        detailtrace = get_detailtrace()
        # 记录错误日志
        logger.error( '\n获取手机号码归属地出错：' + str(e.args) + '\n程序调用堆栈的日志:' + detailtrace + '\nurl: %s\n参数: %s\n' % (url, str(params)))
        return {}

    # 处理返回的内容，去掉多余的字符串
    result = result[result.find('{'): result.rfind("}") + 1]
    # print(result)
    # 将返回内容转为json
    result = json.loads(result)
    if result['data']:
        province = result['data'][0].get('prov', '')
        city = result['data'][0].get('city', '')
        if not province and city in ('北京', '上海', '天津', '重庆'):
            province = city

        # 拼接返回字串
        fields = {
            'mobile': result['data'][0].get('phoneno', ''),
            'province': province,
            'city': city,
            'type': result['data'][0].get('type', '')
        }
    else:
        fields = {}

    # 返回josn
    return fields


def get_phone_number_segment(mobile):
    """
    获取当前手机号码所属运营商
    :param mobile: 手机号码
    :return: '中国移动' or '中国联通' or '中国电信'
    """
    if not mobile or len(str(mobile)) != 11:
        return None

    # 处理特殊号码
    mobile = str(mobile)
    if mobile[0:3] == '170':
        phone_number = mobile[0:4]
    else:
        phone_number = mobile[0:3]

    if phone_number in cm_phone_number_segment:
        return '中国移动'
    elif phone_number in cu_phone_number_segment:
        return '中国联通'
    elif phone_number in ct_phone_number_segment:
        return '中国电信'
    else:
        result = get_QCellCore(mobile)
        if result and result.get('type'):
            return result.get('city', '')
        else:
            return ''
